package com.shujia.day17;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Demo03GetClassVariable {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, InvocationTargetException, InstantiationException, IllegalAccessException {
        /*
            TODO 通过反射的方式获取成员变量
         */
        Class<?> teacherClazz = Class.forName("com.shujia.day17.Teacher");

        // 获取无参构造的对象
        Constructor<?> declaredConstructor = teacherClazz.getDeclaredConstructors()[0];
        declaredConstructor.setAccessible(true);
        Teacher teacher = (Teacher)declaredConstructor.newInstance();

        Field name = teacherClazz.getField("name");
        name.set(teacher,"AI Teacher");
        System.out.println(teacher);

        // TODO 当给定的属性没有权限时
//        Field[] fields = teacherClazz.getFields();
//        for (Field field : fields) {
//            System.out.println(field);
//        }

        // 获取所有权限的属性
        Field[] declaredFields = teacherClazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        Field field = declaredFields[1];
        field.setAccessible(true); // 开启权限
        field.set(teacher,30);
        System.out.println(teacher);

    }
}
